<template>
  <view class="registration-modal" v-if="visible">
    <view class="modal-mask" @click="handleCancel"></view>
    <view class="modal-content">
      <view class="modal-header">
        <text class="modal-title">欢迎注册</text>
        <view class="close-btn" @click="handleCancel">
          <text class="iconfont icon-close">×</text>
        </view>
      </view>
      
      <view class="modal-body">
        <!-- 头像选择 -->
        <view class="avatar-section">
          <text class="section-label">选择头像</text>
          <view class="avatar-container" @click="selectAvatar">
            <image class="avatar-img" :src="selectedAvatar" mode="aspectFill"></image>
            <view class="avatar-overlay">
              <text class="avatar-text">点击选择</text>
            </view>
          </view>
        </view>
        
        <!-- 昵称输入 -->
        <view class="nickname-section">
          <text class="section-label">用户昵称</text>
          <view class="input-container">
            <input 
              class="nickname-input" 
              v-model="nickname" 
              placeholder="请输入您的昵称" 
              maxlength="20"
              @input="validateNickname"
            />
          </view>
          <text class="input-tip" v-if="nicknameError">{{ nicknameError }}</text>
        </view>
      </view>
      
      <view class="modal-footer">
        <button 
          class="register-btn" 
          :class="{ 'disabled': !canRegister }"
          :disabled="!canRegister || registering"
          @click="handleRegister"
        >
          {{ registering ? '注册中...' : '立即注册' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { API_CONFIG } from '@/api/config'

export default {
  name: 'RegistrationModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    openId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      selectedAvatar: '/static/images/default-avatar.png',
      nickname: '',
      nicknameError: '',
      registering: false,
      // 预设头像列表
      avatarList: [
        '/static/images/avatar1.png',
        '/static/images/avatar2.png',
        '/static/images/avatar3.png',
        '/static/images/avatar4.png',
        '/static/images/avatar5.png',
        '/static/images/avatar6.png'
      ]
    }
  },
  computed: {
    canRegister() {
      return this.nickname.trim().length >= 2 && !this.nicknameError && this.openId
    }
  },
  methods: {
    // 选择头像
    selectAvatar() {
      uni.showActionSheet({
        itemList: ['选择预设头像', '从相册选择'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.showAvatarList()
          } else if (res.tapIndex === 1) {
            this.chooseImageFromAlbum()
          }
        }
      })
    },
    
    // 显示预设头像列表
    showAvatarList() {
      const itemList = this.avatarList.map((item, index) => `头像${index + 1}`)
      uni.showActionSheet({
        itemList: itemList,
        success: (res) => {
          this.selectedAvatar = this.avatarList[res.tapIndex]
        }
      })
    },
    
    // 从相册选择头像
    chooseImageFromAlbum() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: (res) => {
          this.selectedAvatar = res.tempFilePaths[0]
        }
      })
    },
    
    // 验证昵称
    validateNickname() {
      const nickname = this.nickname.trim()
      if (nickname.length === 0) {
        this.nicknameError = ''
        return
      }
      if (nickname.length < 2) {
        this.nicknameError = '昵称至少需要2个字符'
        return
      }
      if (nickname.length > 20) {
        this.nicknameError = '昵称不能超过20个字符'
        return
      }
      // 检查特殊字符
      const specialChars = /[<>"'&]/
      if (specialChars.test(nickname)) {
        this.nicknameError = '昵称不能包含特殊字符'
        return
      }
      this.nicknameError = ''
    },
    
    // 生成随机用户名
    generateUsername() {
      const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
      let result = 'user_'
      for (let i = 0; i < 10; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      return result
    },
    
    // 处理注册
    async handleRegister() {
      if (!this.canRegister) return
      
      this.registering = true
      
      try {
        const registrationData = {
          openId: this.openId,
          nickname: this.nickname.trim(),
          avatar: this.selectedAvatar,
          username: this.generateUsername(),
          password: '123456', // 默认密码
          roleId: 2, // 普通角色
          deptId: API_CONFIG.ORG_ID // 使用配置文件中的组织ID，后端会进行类型转换
        }
        
        // 触发注册事件
        this.$emit('register', registrationData)
        
      } catch (error) {
        console.error('注册失败:', error)
        uni.showToast({
          title: '注册失败，请重试',
          icon: 'error'
        })
      } finally {
        this.registering = false
      }
    },
    
    // 取消注册
    handleCancel() {
      this.$emit('cancel')
    },
    
    // 重置表单
    resetForm() {
      this.selectedAvatar = '/static/images/default-avatar.png'
      this.nickname = ''
      this.nicknameError = ''
      this.registering = false
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetForm()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.registration-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.modal-header {
  position: relative;
  padding: 40rpx 40rpx 20rpx;
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  color: #ffffff;
  
  .modal-title {
    font-size: 36rpx;
    font-weight: 600;
    text-align: center;
    display: block;
  }
  
  .close-btn {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.2);
    
    .iconfont {
      font-size: 32rpx;
      color: #ffffff;
    }
  }
}

.modal-body {
  padding: 40rpx;
}

.avatar-section {
  margin-bottom: 40rpx;
  text-align: center;
  
  .section-label {
    display: block;
    font-size: 28rpx;
    color: #333333;
    margin-bottom: 20rpx;
    font-weight: 500;
  }
  
  .avatar-container {
    position: relative;
    width: 120rpx;
    height: 120rpx;
    margin: 0 auto;
    border-radius: 50%;
    overflow: hidden;
    border: 4rpx solid #4A90E2;
    
    .avatar-img {
      width: 100%;
      height: 100%;
    }
    
    .avatar-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;
      
      .avatar-text {
        font-size: 20rpx;
        color: #ffffff;
      }
    }
    
    &:active .avatar-overlay {
      opacity: 1;
    }
  }
}

.nickname-section {
  .section-label {
    display: block;
    font-size: 28rpx;
    color: #333333;
    margin-bottom: 20rpx;
    font-weight: 500;
  }
  
  .input-container {
    position: relative;
    
    .nickname-input {
      width: 100%;
      height: 80rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      border: 2rpx solid #E5E5E5;
      border-radius: 12rpx;
      background-color: #F8F9FA;
      transition: border-color 0.3s;
      
      &:focus {
        border-color: #4A90E2;
        background-color: #ffffff;
      }
    }
  }
  
  .input-tip {
    display: block;
    font-size: 24rpx;
    color: #FF6B6B;
    margin-top: 10rpx;
    padding-left: 20rpx;
  }
}

.modal-footer {
  padding: 20rpx 40rpx 40rpx;
  
  .register-btn {
    width: 100%;
    height: 80rpx;
    background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
    color: #ffffff;
    border: none;
    border-radius: 12rpx;
    font-size: 30rpx;
    font-weight: 600;
    transition: all 0.3s;
    
    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 10rpx rgba(74, 144, 226, 0.3);
    }
    
    &.disabled {
      background: #CCCCCC;
      color: #999999;
      transform: none;
      box-shadow: none;
    }
  }
}
</style>